import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { useUserStore } from '@vben/stores';
import { handleTree } from '@vben/utils';

import { z } from '#/adapter/form';
import { getDeptListCondition } from '#/api/system/dept';
import { getParentPostList } from '#/api/system/post';

const userStore = useUserStore();
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      component: 'Input',
      fieldName: 'options',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'deptId',
      label: '所属部门',
      component: 'ApiTreeSelect',
      disabled: false,
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({});
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择所属单位',
        treeDefaultExpandAll: true,
        autoSelect: 'first',
      },
    },
    {
      component: 'AutoComplete',
      fieldName: 'name',
      label: '岗位',
      rules: 'required',
      defaultValue: '',
      dependencies: {
        triggerFields: ['deptId'],
        // 当 deptId 变化时触发
        trigger: async (values) => {
          if (values.deptId) {
            try {
              const res = await getParentPostList({ deptId: values.deptId });
              values.options = res
                ? res.map((item) => ({
                    value: item.name,
                    label: item.name,
                    code: item.code,
                  }))
                : [];
            } catch (error) {
              console.error('获取岗位列表失败:', error);
              values.options = [];
            }
          } else {
            values.options = [];
          }
        },
      },

      componentProps: (values) => {
        const options = values.options || [];

        const filterOption = (input: string, option: any) => {
          return option.value.toUpperCase().includes(input.toUpperCase());
        };

        return {
          placeholder: '请输入或选择岗位',
          options,
          filterOption,
          onSelect(value: string, option: any) {
            values.code = option.code;
            values.inheritFlag = true; // 设置禁用标志
          },
          onChange(input: string) {
            if (!input) {
              values.code = '';
              values.inheritFlag = false; // 清空时恢复可编辑
            }
          },
        };
      },
    },
    {
      component: 'Input',
      fieldName: 'code',
      label: '岗位编码',
      rules: 'required',
      placeholder: '请输入岗位编码',
      dependencies: {
        triggerFields: ['inheritFlag'],
        disabled: (values) => {
          return values.inheritFlag;
        },
      },
    },
    {
      fieldName: 'sort',
      label: '显示顺序',
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
      rules: 'required',
    },
    {
      fieldName: 'status',
      label: '岗位状态',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(CommonStatusEnum.ENABLE),
    },
    {
      fieldName: 'builtIn',
      label: '本单位使用',
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING, 'boolean'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.boolean().default(true),
    },
    {
      component: 'inheritFlag',
      fieldName: '是否继承上级岗位',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'remark',
      label: '岗位备注',
      component: 'Textarea',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'deptId',
      label: '所属单位',
      component: 'ApiTreeSelect',
      defaultValue: userStore.userInfo.deptId,
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({});
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择所属单位',
        treeDefaultExpandAll: true,
        autoSelect: 'first',
      },
    },
    {
      fieldName: 'name',
      label: '岗位名称',
      component: 'Input',
    },
    {
      fieldName: 'code',
      label: '岗位编码',
      component: 'Input',
    },
    {
      fieldName: 'status',
      label: '岗位状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '岗位编号',
    },
    {
      field: 'name',
      title: '岗位名称',
    },
    {
      field: 'code',
      title: '岗位编码',
    },
    {
      field: 'builtIn',
      title: '是否内置',
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.INFRA_BOOLEAN_STRING },
      },
    },
    {
      field: 'status',
      title: '岗位状态',
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.COMMON_STATUS },
      },
    },
    {
      field: 'sort',
      title: '显示顺序',
    },
    {
      field: 'remark',
      title: '岗位备注',
    },
    {
      field: 'createTime',
      title: '创建时间',
      formatter: 'formatDateTime',
    },
    {
      title: '操作',
      width: 130,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
